﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace KeZhou.Views.Components.Customs
{
    /// <summary>
    /// MessageHost.xaml 的交互逻辑
    /// </summary>
    public partial class MessageHost : ItemsControl
    {
        public MessageHost()
        {
            InitializeComponent();
        }

        public void pushMessage(string title, string content)
        {
            Message message = new Message(title, content);
            // 注册关闭事件的处理函数
            message.CloseButtonClicked += new Message.CloseButtonClickedHandler(closeMessage);
            this.Items.Add(message);

            // 定时关闭
            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(5);
            timer.Tick += (sender, e) =>
            {
                // timer第一次超时时触发message的Removed事件来触发函数
                // 第二次超时才真正从Items中移除message
                if (message.hasRemoved)
                {
                    this.Items.Remove(message);
                    timer.Stop();
                } else
                {
                    message.OnRemoved();
                    timer.Stop();
                    timer.Interval = TimeSpan.FromSeconds(2);
                    timer.Start();
                }
            };
            timer.Start();
        }

        // Message的关闭icon被点击时调用
        public void closeMessage(Message m)
        {
            this.Items.Remove(m);
        }
    }
}
